package cn.demomaster.quickrouter.fragment;

import static android.view.KeyEvent.ACTION_DOWN;
import static android.view.KeyEvent.ACTION_UP;
import static android.view.KeyEvent.KEYCODE_BACK;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.MenuRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import com.demomaster.quickcompat.util.DisplayUtil;
import com.demomaster.quickcompat.view.menu.NavMenu;

import cn.demomaster.quickrouter.R;
import cn.demomaster.quickrouter.actionbar.ActionBarTool;
import cn.demomaster.quickrouter.activity.QuickActivity;
import cn.demomaster.quickrouter.manager.QuickFragmentHelper;
import cn.demomaster.quickrouter.manager.QuickRleaser;

/**
 * Created by Squirrel桓 on 2019/1/3.
 */
public abstract class QuickFragment extends Fragment implements ViewLifecycle, View.OnClickListener {
    public static String TAG = QuickFragment.class.getName();
    public AppCompatActivity mContext;
    public int containerViewId;

    //是否使用自定义导航
    @Override
    public boolean isUseActionBarLayout() {
        return true;
    }

    @Override
    public boolean isTransparencyBar() {
        return true;
    }

    @Override
    public boolean canDrag() {
        return true;
    }

    @Override
    public void onDragFinish() {
        finish();
    }
    public QuickFragment() {
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = (AppCompatActivity) this.getContext();
        initMenu();
        Log.i(TAG,"onCreate$" + hashCode() + "-" + getClass().getSimpleName()+",mContext="+mContext);
        //StatusBarUtil.transparencyBar(new WeakReference<>(mContext));
    }

    public <T extends View> T findViewById(int id) {
        if (getView() == null) {
            return null;
        }
        return getView().findViewById(id);
    }

    public View getHeaderlayout() {
        return inflateView(R.layout.qd_activity_actionbar_common);
    }

    public View inflateView(int layoutId) {
        return LayoutInflater.from(mContext).inflate(layoutId, null);
    }

    //是否可以被点击 false点击穿透
    private boolean clickable = true;

    public void setClickable(boolean clickable) {
        this.clickable = clickable;
    }

    private String mTitle;

    public void setTitle(String title) {
        this.mTitle = title;
        if (getActionBarTool() != null) {
            getActionBarTool().setTitle(title);
        }
    }

    public String getTitle() {
        return mTitle;
    }

    //View itv_action_right;
    View fragmentView;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //return super.onCreateView(inflater, container, savedInstanceState);
        View view = onGenerateView(inflater, container, savedInstanceState);
        if (isUseActionBarLayout()) {
            //生成最終的view
            fragmentView = decorateView(view);
            getActionBarTool().setTitle(getTitle());
            if (getActionBarTool() != null) {
                getActionBarTool().setLeftOnClickListener(this);
                //itv_action_right = getActionBarTool().getLeftView();
            }
            setThemeColor(view);
        } else {
            fragmentView = view;
        }
        fragmentView.setClickable(clickable);// 防止点击穿透，底层的fragment响应上层点击触摸事件
        return fragmentView;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.it_actionbar_common_left) {
            onClickBack();
        }
    }

    @Override
    public View getView() {
        if (super.getView() != null) {
            return super.getView();
        } else {
            return fragmentView;
        }
    }

    /**
     * 对传递过来的view 再次包装
     *
     * @param view
     * @return
     */
    public View decorateView(View view) {
        if (isUseActionBarLayout()) {//是否使用自定义导航栏
            ActionBarTool.Builder actionBarbuilder = getActivityLayoutBuilder(mContext);
            actionBarbuilder.setContentView(view);
            View mActionBarLayout = getActionBarTool().genarateView(actionBarbuilder);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                mActionBarLayout.setId(View.generateViewId());
            }
            return mActionBarLayout;
        } else {
            return view;
        }
    }

    public ActionBarTool.Builder getActivityLayoutBuilder(Activity mContext) {
        ActionBarTool.Builder builder = new ActionBarTool.Builder(mContext)
                .setActionBarView(getHeaderlayout())
                .setStatusHeight(DisplayUtil.getStatusBarHeight(mContext))
                .setContentViewPaddingTop(ActionBarTool.PaddingWith.none)
                .setMixStatusActionBar(true);
        return builder;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //QdLog.d("onViewCreated");
        initCreatView(view);
        initOptionsMenu(navigationMenu);
    }

    public void setThemeColor(View fragmentView) {
        if (fragmentView != null && fragmentView.getBackground() == null) {//设置默认颜色
            int backgroundColor = Color.TRANSPARENT;
            if (getActionBarTool() != null) {
                backgroundColor = getActionBarTool().getThemeBackgroundColor();
            }
            fragmentView.setBackgroundColor(backgroundColor);
        }
    }

    public void initCreatView(View contentView) {
        initView(contentView);
    }

    @SuppressLint("RestrictedApi")
    public void onClickBack() {
        //模拟点击
        int eventCode = KEYCODE_BACK;//ACTION_DOWN
        long now = SystemClock.uptimeMillis();
        KeyEvent down = new KeyEvent(now, now, ACTION_DOWN, eventCode, 0);
        down.setSource(257);
        down = KeyEvent.changeFlags(down, 8);

        if (getActivity() == null) {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            getActivity().dispatchKeyEvent(down);
            now = SystemClock.uptimeMillis();
            KeyEvent up = new KeyEvent(now, now, ACTION_UP, eventCode, 0);
            up.setSource(257);
            up = KeyEvent.changeFlags(down, 520);
            if (getActivity() != null) {
                getActivity().dispatchKeyEvent(up);
            }
        } else {
            getActivity().onBackPressed();
        }
        //getActivity().onKeyUp(eventCode, up);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.i(TAG,"$" + hashCode() + "-" + getClass().getSimpleName() + ":" + (hidden ? "隐藏" : "显示") + ",isVisible=" + isVisible());
        if (!hidden && isAdded() && getActivity() != null) {
            doResume();
        }
    }
    NavMenu navigationMenu;

    /**
     * 此处可自定义返回menu配置文件id
     * @return
     */
    @SuppressLint("RestrictedApi")
    public @MenuRes int getMenuRes() {
        return  -1;
    }
    private void initMenu(){
        if(getMenuRes()!=-1) {
            navigationMenu = new NavMenu(mContext);
            getActivity().getMenuInflater().inflate(getMenuRes(), navigationMenu);
        }
    }

    public void initOptionsMenu(Menu menu) {

    }
    @Override
    public void onCreateContextMenu(@NonNull ContextMenu menu, @NonNull View v, @Nullable ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        Log.i(TAG,"onCreateContextMenu");
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        //inflater.inflate(R.menu.main,menu);
        initOptionsMenu(menu);
        Log.i(TAG,"onCreateOptionsMenu");
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    private ActionBarTool actionBarTool;
    //获取自定义导航
    public ActionBarTool getActionBarTool() {
        if (actionBarTool == null) {
            Log.i(TAG,"mContext="+mContext);
            actionBarTool = new ActionBarTool(this);
        }
        return actionBarTool;
    }

    public QuickFragmentHelper getFragmentHelper() {
        if (getActivity() instanceof QuickActivity) {
            return ((QuickActivity) getActivity()).getFragmentHelper();
        }
        return null;
    }

    public void startFragment(QuickFragment fragment, Integer parentId, Intent intent) {
        if (getFragmentHelper() != null) {
            //getFragmentHelper().navigate(mContext, fragment, parentId, intent);
            getFragmentHelper().build(mContext)// WebViewFragment.class.getName())//
                    .setFragment(fragment)
                    .setContainerViewId(parentId)
                    .setIntent(intent)
                    .navigation();
        }
    }

    public void startActivity(Class<?> clazz) {
        startActivity(clazz, null);
    }

    public void startActivity(Class<?> clazz, Bundle bundle) {
        Intent intent = new Intent(getContext(), clazz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
        mContext.overridePendingTransition(R.anim.translate_from_right_to_left_enter, R.anim.anim_null);
    }


    int mResultCode;
    Intent mResultData;

    public void setResult(int resultCode, Intent data) {
        mResultCode = resultCode;
        mResultData = data;
    }

    int mRequestCode;
    ViewLifecycle fromFragment;

    public void setRequestCode(int requestCode,ViewLifecycle qdFragmentInterface) {
        mRequestCode = requestCode;
        fromFragment = qdFragmentInterface;
    }

    Intent mIntent;

    @Override
    public void setIntent(Intent intent) {
        mIntent = intent;
        if (intent != null) {
            setArguments(intent.getExtras());
        }
    }

    public Intent getIntent() {
        return mIntent;
    }
    @Override
    public void onStart() {
        super.onStart();
        //QdLog.i("onStart$"+hashCode()+"-"+getClass().getSimpleName());
    }

    @Override
    public void onFragmentStart() {

    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.i(TAG,"onSaveInstanceState"+hashCode()+"-"+getClass().getSimpleName());
    }

   // boolean isResumed;

    @Override
    public void doResume() {
        Log.i(TAG,"doResume isResumed=" + isResumed() + ",hide=" + isHidden());
        if (!isResumed()) {
            onResume();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i(TAG,"onResume$"+hashCode()+"-"+getClass().getSimpleName()+",isHidden="+isHidden()+",isVisible="+isVisible());
        //isResumed = true;
        isPaused = false;
        if (!isHidden()) {
            onFragmentResume();
        }
    }

    @Override
    public void onFragmentResume() {
        Log.i(TAG,"onFragmentResume$" + hashCode() + "-" + getClass().getSimpleName());
    }

    boolean isPaused;

    @Override
    public void doPause() {
        if (!isPaused) {
            onPause();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        //QdLog.i( "onPause$"+hashCode()+"-"+getClass().getSimpleName()+",isHidden="+isHidden()+",isVisible="+isVisible());
        isPaused = true;
      //  isResumed = false;
        if (!isHidden()) {
            onFragmentPause();
        }
    }

    @Override
    public void onFragmentPause() {
        Log.i(TAG,"onFragmentPause$" + hashCode() + "-" + getClass().getSimpleName());
    }

    @Override
    public void onStop() {
        super.onStop();
        //QdLog.i("onStop$"+hashCode()+"-"+getClass().getSimpleName()+",isHidden="+isHidden()+",isVisible="+isVisible());
        if (!isHidden()) {
            onFragmentStop();
        }
    }

    @Override
    public void onFragmentStop() {
        Log.i(TAG,"onFragmentStop$" + hashCode() + "-" + getClass().getSimpleName());
    }

    boolean finishWithActivity;

    public void setFinishWithActivity(boolean finishWithActivity) {
        this.finishWithActivity = finishWithActivity;
    }

    public void finish() {
        onfinish();
        // onClickBack();
        if (finishWithActivity) {
            getActivity().finish();
        } else {
            if (getFragmentHelper() != null) {
                getFragmentHelper().popBackStack(this);
            } else {
                if (getFragmentManager() != null) {
                    getFragmentManager().popBackStack();
                }
            }
        }
    }
    public void onfinish(){

    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.i(TAG,"onDetach$" + hashCode() + "-" + getClass().getSimpleName());
    }

    @Override
    public void onDestroyView() {
        if (actionBarTool != null) {
            actionBarTool.onRelease(this);
        }
        super.onDestroyView();
        Log.i(TAG,"onDestroyView$" + hashCode() + "-" + getClass().getSimpleName());
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        Log.i(TAG,"onLowMemory$" + hashCode() + "-" + getClass().getSimpleName());
    }

    @Override
    public void onDestroy() {
        if (fromFragment != null) {
            fromFragment.onActivityResult(mRequestCode, mResultCode, mResultData);
        }
        mResultData = null;
        fromFragment = null;
       /* if (action_button_left_onclicklistener != null) {
            action_button_left_onclicklistener.onRelease(this);
        }*/
//        if (EventBus.getDefault().isRegistered(this)) {
//            EventBus.getDefault().unregister(this);
//        }
        QuickRleaser.release(this);
        super.onDestroy();
    }

    public boolean isRootFragment() {
        return getFragmentHelper().isRootFragment(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.i(TAG,getClass().getName() + "-onKeyDown keyCode=" + keyCode);
        if (keyCode == KeyEvent.KEYCODE_BACK) {//默认只处理回退事件
            if (!isRootFragment()) {
                //getActivity().onBackPressed();
                finish();
            } else {//已经是根fragment了
                Log.i(TAG,getClass().getName() + "-已经是根fragment了");
                //onKeyDownRootFragment(keyCode,event);
            }
            return true;//当返回true时，表示已经完整地处理了这个事件，并不希望其他的回调方法再次进行处理，而当返回false时，表示并没有完全处理完该事件，更希望其他回调方法继续对其进行处理
        } else {//其他事件自行处理
            return false;
        }
    }

   /* public void onKeyDownRootFragment(int keyCode, KeyEvent event){
        if (getFragmentHelper() != null) {
            getFragmentHelper().onKeyDown(this);
        } else {
            if (getFragmentManager() != null) {
                getFragmentManager().popBackStack();
            }
        }
    }*/
}
